/*
* Copyright (c) 2012 Kyle Hayward
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "Precompiled.h"

#include "Acceleration.h"
#include "Context.h"
#include "BufferStream.h"

using namespace System;
using namespace System::IO;

namespace OptixDotNet 
{
	Acceleration::Acceleration( Context^ context, AccelBuilder builder, AccelTraverser traverser ) : OptixNode( context )
	{
		pin_ptr<RTacceleration> ptr = &mAccel;
		CheckError( rtAccelerationCreate( context->InternalPtr(), ptr ) );

		Builder = builder;
		Traverser = traverser;

		MarkAsDirty();
	}

	Acceleration::Acceleration( Context^ context, RTacceleration accel ) : OptixNode( context )
	{
		mAccel = accel;

		const char* str = 0;
		CheckError( rtAccelerationGetBuilder( mAccel, &str ) );
		mBuilder = (AccelBuilder)System::Enum::Parse( mBuilder.GetType(), AnsiiToStr( str ) );

		str = 0;
		CheckError( rtAccelerationGetTraverser( mAccel, &str ) );
		mTraverser = (AccelTraverser)System::Enum::Parse( mTraverser.GetType(), AnsiiToStr( str ) );
	}

	bool Acceleration::Save( String^ path )
	{
		return Data->Save( path );
	}

	bool Acceleration::Load( String^ path )
	{
		if( File::Exists( path ) )
		{
			BufferStream^ data = gcnew BufferStream( File::OpenRead( path ) );

			if( data != nullptr )
			{
				Data = data;
				return true;
			}
		}

		return false;
	}

	BufferStream^ Acceleration::Data::get()
	{
		RTsize size;
		CheckError( rtAccelerationGetDataSize( mAccel, &size ) );

		char* data = new char[ size ];
		CheckError( rtAccelerationGetData( mAccel, data ) );

		return gcnew BufferStream( data, size, true, false, true );
	}

	void Acceleration::Data::set( BufferStream^ stream )
	{
		CheckError( rtAccelerationSetData( mAccel, (void*)stream->DataPointer.ToPointer(), (RTsize)stream->Length ) );
	}
}